<template>
  <div class="app-container">
    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
    <el-table
      :data="tableData"
      border
      highlight-current-row
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column
        v-for="item of tableHeader"
        :key="item"
        :prop="item"
        :label="item"
      />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { importEmployee } from '@/api/employees'
import { formatExcelDate } from '@/utils/index'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 处理成功的回调函数
    // 1.将excel文件中的数据读取出来转化为js数据
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      console.log('results', results, 'header', header)
      // 2.将excel读取出来的数据格式化
      const data = this.transExcel(results)
      console.log(data, '格式化后英文')
      // 3.发送请求,实现批量添加
      this.Impory(data)
      // 回退页面
      this.$router.back()
    },
    // 格式化 中文转英文
    transExcel(data) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      const result = data.map((zhObj) => {
        // 1. 遍历取值 Object.keys(对象) 返回的是对象中的key,返回值是一个数组
        const zhkeys = Object.keys(zhObj)
        //    console.log(zhkeys);  //['入职日期', '姓名', '工号', '手机号', '转正日期', '部门']
        //    2.储存的英文对象
        const enkeyObj = {}
        zhkeys.map((enkey) => {
          const enkeys = mapInfo[enkey] // 英文的key
          // console.log(enkeys);
          // 处理时间格式
          if (enkeys === 'timeOfEntry' || enkeys === 'correctionTime') {
            enkeyObj[enkeys] = formatExcelDate(zhObj[enkey])
          } else {
            enkeyObj[enkeys] = zhObj[enkey] // 键名:值
          }
        })
        console.log(enkeyObj) // {timeOfEntry: 44506, username: '小李', workNumber: 9006, mobile: '13810000512', correctionTime: 44893,…}
        return enkeyObj
      })
      return result
    },
    // 批量添加的函数
    async Impory(data) {
      try {
        const res = await importEmployee(data)
        console.log(res, '批量成功')
      } catch (error) {
        console.log(error)
      }
    }

  }
}
</script>
